package com.durian.base.update.proxy.impl

import com.durian.base.rxhttp.RxHttp
import com.durian.base.rxhttp.param.toDownload
import com.durian.base.update.XUpdate
import com.durian.base.update.entity.DownloadEntity
import com.durian.base.update.proxy.DownloadApkCallBack
import com.durian.base.update.proxy.IHttpRequest
import com.durian.base.utils.CoroutineKt
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * 说明：DefaultHttpRequest
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2021/10/21 8:14 下午
 * <p/>
 * 版本：version 1.0
 */

fun XUpdate.cancel(){
    RxHttp.cancelTag(DefaultHttpRequest.Tag)
}

abstract class DefaultHttpRequest : IHttpRequest{

    companion object{
        val Tag = "XUPDATE_001"
    }

    override fun downloadApk(downloadEntity: DownloadEntity, callBack: DownloadApkCallBack) {
        CoroutineKt.Scope.launch {
            kotlin.runCatching {
                XUpdate.setDownloading(true)
                RxHttp.get(downloadEntity.versionEntity.downloadUrl)
                    .tag(Tag)
                    .toDownload(downloadEntity.apkFileTemp,true){
                        XUpdate.setDownloading(true)
                        callBack.onProgress(it.currentSize,it.totalSize)
                    }.catch {
                        XUpdate.setDownloading(false)
                        callBack.onError(null)
                    }.collect {
                        XUpdate.setDownloading(false)
                        downloadEntity.downloadSuccess()
                        callBack.onFinish(downloadEntity)
                    }
            }
        }
    }
}